﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using SASystem.SAServiceRef;

namespace SASystem
{
    public partial class FamilyEditFrm : Form
    {
        enum PageIndex
        {
            PageOne = 1,
            PageTwo,
            PageThree
        }

        private List<ParameterInfo> m_curExcelParameters;
        private List<ParameterInfo> m_curKeyParameters;
        private Guid m_curFamilyId;

        private FamilyInfo m_editFamilyInfo;
        private FamilyAttrInfo m_editFamilyAttrInfo;
        
        public FamilyEditFrm(FamilyInfo editFamilyInfo)
        {
            InitializeComponent();
            m_editFamilyInfo = editFamilyInfo;

        }

        //shared.
        private void PublishFrm_Load(object sender, EventArgs e)
        {
            InitCommonData();
            InitSpecialData();
        }

        private void button_Done_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button_wizardPrevious_Click(object sender, EventArgs e)
        {
            int curIdx = this.tabControl_wizard.SelectedIndex;
            if (curIdx == 0)
            {
                return;
            }

            this.tabControl_wizard.SelectedIndex = curIdx - 1;
            this.button_wizardNext.Enabled = true;

            if (this.tabControl_wizard.SelectedIndex == 0)
            {
                this.button_wizardPrevious.Enabled = false;
            }
            else
            {
                this.button_wizardPrevious.Enabled = true;
            }

            this.button_publish.Visible = false;
        }

        private void button_wizardNext_Click(object sender, EventArgs e)
        {
            int curIdx = this.tabControl_wizard.SelectedIndex;

            if (curIdx == 0)
            {
                if (!this.CheckInputForPageOne()) return;

                this.tabControl_wizard.SelectedIndex = curIdx + 1; //the second page
                this.button_wizardPrevious.Enabled = true;
                this.button_wizardNext.Enabled = true;
                this.button_publish.Visible = false;

                //set the model path to window title.
                //this.Text = this.textBox_partPath.Text;
            }
            else if (curIdx == 1)
            {
                if (!this.CheckInputForPageTwo()) return;

                this.tabControl_wizard.SelectedIndex = curIdx + 1; //this third page.
                this.button_wizardPrevious.Enabled = true;
                this.button_wizardNext.Enabled = false;
                this.button_publish.Visible = true;
            }
            else if (curIdx == 2)
            {
                return;
            }

            return;
        }

        //page one.
        //init methods.
        private void InitCommonData()
        {
            SABLL.InitVendorComboBoxView(this.comboBox_venderList);
            SABLL.InitStandardComboBoxView(this.comboBox_standardList);
            SABLL.InitCategoryTreeView(this.treeView_categoryList);
        }

        private void InitSpecialData()
        {
            this.button_wizardPrevious.Enabled = false;
            this.button_publish.Visible = false;
            m_curFamilyId = m_editFamilyInfo.ID; //edit family
            string familyId = m_editFamilyInfo.ID.ToString();
            m_editFamilyAttrInfo = SABLL.GetFamilyAttrInfo(m_editFamilyInfo.ID);

            //page one
            //
            //string tempFilePath = Path.Combine(SABLL.GetTempFolder(m_curFamilyId), m_editFamilyAttrInfo.TemplateFileName);
            string modelPicPath = Path.Combine(SABLL.GetLocalCacheFolder(familyId), m_editFamilyAttrInfo.ModelPicName);
            string drawPicPath = Path.Combine(SABLL.GetLocalCacheFolder(familyId), m_editFamilyAttrInfo.DrawPicName);
            string drawingPath = Path.Combine(SABLL.GetLocalCacheFolder(familyId), m_editFamilyAttrInfo.DrawingName);
            string referencePath = Path.Combine(SABLL.GetLocalCacheFolder(familyId), m_editFamilyAttrInfo.ReferenceName);

            //SABLL.SaveBinaryByPath(tempFilePath, m_editFamilyAttrInfo.TemplateFileBinary);
            SABLL.SaveBinaryByPath(modelPicPath, m_editFamilyAttrInfo.ModelPicBinary);
            SABLL.SaveBinaryByPath(drawPicPath, m_editFamilyAttrInfo.DrawPicBinary);
            SABLL.SaveBinaryByPath(drawingPath, m_editFamilyAttrInfo.DrawingBinary);
            SABLL.SaveBinaryByPath(referencePath, m_editFamilyAttrInfo.ReferenceBinary);

            if (System.IO.File.Exists(modelPicPath)) this.textBox_familyPic.Text = modelPicPath;
            if (System.IO.File.Exists(drawingPath)) this.textBox_familyDwg.Text = drawingPath;
            if (System.IO.File.Exists(drawPicPath)) this.textBox_familyDwgPic.Text = drawPicPath;
            if (System.IO.File.Exists(referencePath)) this.textBox_familyTechDoc.Text = referencePath;
            this.textBox_familyName.Text = m_editFamilyInfo.Name;
            this.richTextBox_familyDescription.Text = m_editFamilyAttrInfo.Description;

            VendorInfo vendorInfo = SABLL.GetVendor(m_editFamilyInfo.VendorID);
            if (vendorInfo != null) this.comboBox_venderList.Text = vendorInfo.Name;

            StandardInfo standardInfo = SABLL.GetStandard(m_editFamilyInfo.StandardID);
            if (standardInfo != null) this.comboBox_standardList.Text = standardInfo.Name;
            
            //select category tree node.
            Guid cateGuid = m_editFamilyInfo.CategoryID;
            SABLL.SelectNode(this.treeView_categoryList, cateGuid);

            //page two
            //
            m_curExcelParameters = SABLL.GetFamilyParameters(m_curFamilyId);
            SABLL.InitExcelParametersTreeView(this.treeView_excelParams, m_curExcelParameters);

            m_curKeyParameters = m_curExcelParameters.Where(s => s.IsKey == true).OrderBy(s => s.Idx).ToList<ParameterInfo>();
            SABLL.InitKeyParametersGridView(this.dataGridView_paramsEditor, m_curKeyParameters);

            //page three
            //
            SABLL.InitFamilyTableGridView(this.dataGridView_familyTable, m_curFamilyId);

            //set family table column header text.
            //
            for (int i = 0; i < m_curExcelParameters.Count && i < this.dataGridView_familyTable.ColumnCount - 2; i++ )
            {
                string columnHeaderText = String.Empty;
                columnHeaderText = m_curExcelParameters[i].Name;

                this.dataGridView_familyTable.Columns[i + 2].HeaderText = columnHeaderText;
            }

            //hidden instance id, and cache folder.
            this.dataGridView_familyTable.Columns[0].Visible = false;
            this.dataGridView_familyTable.Columns[1].Visible = false;
        }

        private void button_partPathBrowser_Click(object sender, EventArgs e)
        {
           //this.textBox_partPath.Text = SABLL.OpenFileBrowser(FileType.kModel);

           // //get & set the file name.
           //this.textBox_familyName.Text = Path.GetFileName(this.textBox_partPath.Text);
           
        }

        private void button_familyPicBrowser_Click(object sender, EventArgs e)
        {
            this.textBox_familyPic.Text = SABLL.OpenFileBrowser(FileType.kPicture);
        }

        private void button_familyDwgPicBrowser_Click(object sender, EventArgs e)
        {
            this.textBox_familyDwgPic.Text = SABLL.OpenFileBrowser(FileType.kPicture);
        }

        private void button_familyDwgBrowser_Click(object sender, EventArgs e)
        {
            this.textBox_familyDwg.Text = SABLL.OpenFileBrowser(FileType.kDrawing);
        }

        private void button_familyTechDocBrowser_Click(object sender, EventArgs e)
        {
            this.textBox_familyTechDoc.Text = SABLL.OpenFileBrowser(FileType.kDocument);
        }

        private bool CheckInputForPageOne()
        {
            /*
            if (String.IsNullOrEmpty(this.textBox_partPath.Text))
            {
                SABLL.ShowInfoMsg(@"模型文件路径不能为空！");
                return false;
            }

            if (!File.Exists(this.textBox_partPath.Text))
            {
                SABLL.ShowInfoMsg(@"模型文件不存在！");
                return false;
            }
            */

            if (String.IsNullOrEmpty(this.textBox_familyName.Text))
            {
                SABLL.ShowInfoMsg(@"模型文件名不能为空！");
                return false;
            }



            if (this.treeView_categoryList.SelectedNode == null)
            {
                SABLL.ShowInfoMsg(@"类别不能为空,请选择类别！");
                return false;
            }

            return true;
        }

        private bool CheckInputForPageTwo()
        {
            /*
            if (this.treeView_excelParams.Nodes.Count == 0)
            {
                SABLL.ShowInfoMsg(@"Excel参数列表不能为空！");
                return false;
            }

            if (this.dataGridView_paramsEditor.Rows.Count == 0)
            {
                SABLL.ShowInfoMsg(@"驱动参数列表不能为空！");
                return false;
            }
             */

            int cnt = this.dataGridView_paramsEditor.Rows.Count;

            for (int i = 0; i < cnt; i++)
            {
                ParameterInfo curParam = this.dataGridView_paramsEditor.Rows[i].Tag as ParameterInfo;
                if (curParam == null)
                {
                    continue;
                }

                //only check drive paramters.
                if (curParam.IsDriver)
                {
                    string tag = Convert.ToString(this.dataGridView_paramsEditor.Rows[i].Cells[3].Value);

                    if (!SABLL.CheckTag(tag))
                    {
                        SABLL.ShowInfoMsg(String.Format("无法识别驱动参数[{0}]的属性值[{1}], 请检查属性值规范，然后重新设置!", curParam.Name, tag));
                        return false;
                    }
                }
            }

            return true;
        }

        private bool CheckInputForPageThree()
        {
            return true;
        }

        //page two.
        private void button_getTemplateParams_Click(object sender, EventArgs e)
        {
        }

        private void button_getExcelParams_Click(object sender, EventArgs e)
        {
        }


        private void button_publish_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            this.button_publish.Enabled = false;
            bool success = DoPublish();
            this.button_publish.Enabled = true;
            this.Cursor = Cursors.Default;

            if (success == true)
            {
                this.Close();
            }
        }

        private bool DoPublish()
        {
            FamilyInfo familyInfo = CollectFamilyInfo();
            FamilyAttrInfo familyAttrInfo = CollectFamilyAttrInfo();
            FamilyTableInfo familyTableInfo = CollectFamilyTableInfo();

            bool success = SABLL.UpdateFamily(familyInfo, familyAttrInfo, familyTableInfo);

            if (success)
            {
                SABLL.ShowInfoMsg("发布成功！");
            }
            else
            {
                SABLL.ShowErrMsg("发布失败！" + SABLL.GetLastErrMsg());
            }

            return success;
        }

        private FamilyInfo CollectFamilyInfo()
        {
            FamilyInfo familyInfo = m_editFamilyInfo;
            //familyInfo.ID = m_curFamilyId;
            familyInfo.Name = this.textBox_familyName.Text;
            familyInfo.IsCached = false;

            //standard id
            StandardItem curStandardItem = this.comboBox_standardList.SelectedItem as StandardItem;
            if (curStandardItem != null)
            {
                familyInfo.StandardID = curStandardItem.StandardInfo.StandardId;
            }
            else
                familyInfo.StandardID = -1;

            //vendor id
            VendorItem curVendorItem = this.comboBox_venderList.SelectedItem as VendorItem;
            if (curVendorItem != null)
            {
                familyInfo.VendorID = curVendorItem.VendorInfo.VendorId;
            }
            else
                familyInfo.VendorID = -1;

            //get selected category.
            //
            TreeNode selectedNode = this.treeView_categoryList.SelectedNode;
            CategoryInfo curCategoryInfo = selectedNode.Tag as CategoryInfo;

            familyInfo.CategoryID = curCategoryInfo.Id;
            familyInfo.DisplayName = this.textBox_familyName.Text;

            return familyInfo;
        }

        private FamilyTableInfo CollectFamilyTableInfo()
        {
            FamilyTableInfo retInfo = new FamilyTableInfo();
            retInfo.FamilyID = m_curFamilyId;

            //need to compute parameter edit datagridview.
            //
            int keyParamCnt = this.dataGridView_paramsEditor.Rows.Count;
            for (int i = 0; i < keyParamCnt; i++)
            {
                DataGridViewRow curRow = this.dataGridView_paramsEditor.Rows[i];
                if (curRow.Tag == null) continue;
                ParameterInfo curKeyParamInfo = curRow.Tag as ParameterInfo;
                if (curKeyParamInfo == null) continue;

                curKeyParamInfo.IsKey = true;
                curKeyParamInfo.Idx = i+1;
                curKeyParamInfo.DisplayName = Convert.ToString(curRow.Cells[1].Value);

                if (curKeyParamInfo.IsDriver)
                {
                    curKeyParamInfo.IsCustom = Convert.ToBoolean(curRow.Cells[2].Value);
                    if (curKeyParamInfo.IsCustom)
                    {
                        curKeyParamInfo.Tag = Convert.ToString(curRow.Cells[3].Value);
                    }
                }
            }

            retInfo.Parameters = m_curExcelParameters.ToArray();

            DataTable retTable = new DataTable();
            retTable.TableName = "FamilyTable";
            int columnCnt = this.dataGridView_familyTable.ColumnCount;
            int rowCnt = this.dataGridView_familyTable.Rows.Count;

            //add columns.
            for (int c = 0; c < columnCnt; c++)
            {
                string title = Convert.ToString(this.dataGridView_familyTable.Columns[c].HeaderText);

                retTable.Columns.Add(title, System.Type.GetType("System.String"));
            }

            //add rows.
            for (int r = 0; r < rowCnt; r++)
            {
                DataRow newRow = retTable.NewRow();

                //if all values are empty, don't save it.
                bool allEmtpy = true;
                for (int j = 0; j < columnCnt; j++)
                {
                    string cellVal = Convert.ToString(this.dataGridView_familyTable.Rows[r].Cells[j].Value);
                    if (allEmtpy && !String.IsNullOrEmpty(cellVal))
                    {
                        allEmtpy = false;
                    }
                    newRow[j] = cellVal;
                }
                if (!allEmtpy)
                {
                    retTable.Rows.Add(newRow);
                }
            }

            retInfo.FamilyTable = retTable;
            //
            // retInfo.Parameters
            return retInfo;
        }

        private FamilyAttrInfo CollectFamilyAttrInfo()
        {
            FamilyAttrInfo retInfo = new FamilyAttrInfo();
            retInfo.FamilyID = m_curFamilyId;
            retInfo.Vendor = this.comboBox_venderList.Text;
            retInfo.Description = this.richTextBox_familyDescription.Text;

            //string templateFileName = this.textBox_partPath.Text.Trim();
            string drawingName = this.textBox_familyDwg.Text.Trim();
            string drawPicName = this.textBox_familyDwgPic.Text.Trim();
            string modelPicName = this.textBox_familyPic.Text.Trim();
            string referenceName = this.textBox_familyTechDoc.Text.Trim();

            //get the binaries.
            //
            //retInfo.TemplateFileName = Path.GetFileName(templateFileName);
            //retInfo.TemplateFileBinary = SABLL.GetBinaryByPath(templateFileName);
       
            retInfo.DrawingName = Path.GetFileName(drawingName);
            retInfo.DrawingBinary = SABLL.GetBinaryByPath(drawingName);

            retInfo.DrawPicName = Path.GetFileName(drawPicName);
            retInfo.DrawPicBinary = SABLL.GetBinaryByPath(drawPicName);

            retInfo.ModelPicName = Path.GetFileName(modelPicName);
            retInfo.ModelPicBinary = SABLL.GetBinaryByPath(modelPicName);

            retInfo.ReferenceName = Path.GetFileName(referenceName);
            retInfo.ReferenceBinary = SABLL.GetBinaryByPath(referenceName);

            return retInfo;
        }

        private ParameterInfo GetSelectedNodeParameterInfo()
        {
            TreeNode curNode = this.treeView_excelParams.SelectedNode;
            if (curNode == null)
            {
                SABLL.ShowInfoMsg(@"请先选择可用参数！");
                return null;
            }

            if (curNode.Tag == null) //this is sub node.
                curNode = curNode.Parent;

            if (curNode == null)
            {
                SABLL.ShowInfoMsg(@"所选节点无效，请重新选择！");
                return null;
            }

            ParameterInfo curParam = curNode.Tag as ParameterInfo;
            if (curParam == null)
            {
                SABLL.ShowErrMsg(@"所选节点参数数据丢失, 请重新选择！");
                return null;
            }

            if (curParam.IsKey)
            {
                SABLL.ShowErrMsg(String.Format("参数[{0}]已经设置为关键参数, 不能重复添加！", curParam.Name));
                return null;
            }

            return curParam;
        }

        private void AddParameterInfoIntoEditGridView(ParameterInfo curParam)
        {
            this.dataGridView_paramsEditor.AllowUserToAddRows = true;
            int newRowIndex = this.dataGridView_paramsEditor.Rows.Add();
            this.dataGridView_paramsEditor.AllowUserToAddRows = false;

            DataGridViewRow newRow = this.dataGridView_paramsEditor.Rows[newRowIndex];
            newRow.Tag = curParam;
            newRow.Cells[0].Value = curParam.Name;
            newRow.Cells[1].Value = curParam.DisplayName;
            DataGridViewCheckBoxCell curCheckBoxCell = (DataGridViewCheckBoxCell)newRow.Cells[2];

            if (!curParam.IsDriver)
            {
                curCheckBoxCell.Value = false;
                curCheckBoxCell.ReadOnly = true;
                curCheckBoxCell.Style.BackColor = Color.LightGray;
                newRow.Cells[3].ReadOnly = true;
                newRow.Cells[3].Style.BackColor = curCheckBoxCell.Style.BackColor;
            }
            else
            {
                newRow.Cells[0].Style.ForeColor = Color.Red;
                curCheckBoxCell.Value = curParam.IsCustom;
                curCheckBoxCell.ReadOnly = false;
                newRow.Cells[3].ReadOnly = false;
            }
            this.dataGridView_paramsEditor.ClearSelection();
            newRow.Selected = true;

            //set the parameter key to true when added.
            curParam.IsKey = true;
        }

        private void button_selectParam_Click(object sender, EventArgs e)
        {
            ParameterInfo curParam = GetSelectedNodeParameterInfo();

            if (curParam == null)
            {
                return;
            }

            AddParameterInfoIntoEditGridView(curParam);
        }

        private void button_deleteKeyParam_Click(object sender, EventArgs e)
        {
            DataGridViewRow selectedRow = SABLL.GetSelectedRow(this.dataGridView_paramsEditor);

            if (selectedRow != null)
            {
                ParameterInfo curKeyParam = selectedRow.Tag as ParameterInfo;

                this.dataGridView_paramsEditor.Rows.Remove(selectedRow);

                if (curKeyParam != null)
                {
                    //set the parameter key to false when removed.
                    curKeyParam.IsKey = false;
                    curKeyParam.Idx = 0;
                }
            }
        }

        private void button_moveUp_Click(object sender, EventArgs e)
        {
            DataGridViewRow selectedRow = SABLL.GetSelectedRow(this.dataGridView_paramsEditor);
            if (selectedRow != null && selectedRow.Index > 0)
            {
                int pos = selectedRow.Index - 1;
                this.dataGridView_paramsEditor.Rows.Remove(selectedRow);
                this.dataGridView_paramsEditor.Rows.Insert(pos, selectedRow);
                this.dataGridView_paramsEditor.ClearSelection();
                selectedRow.Selected = true;
            }
        }

        private void button_moveDown_Click(object sender, EventArgs e)
        {
            DataGridViewRow selectedRow = SABLL.GetSelectedRow(this.dataGridView_paramsEditor);
            if (selectedRow != null && selectedRow.Index < this.dataGridView_paramsEditor.Rows.Count - 1)
            {
                int pos = selectedRow.Index + 1;
                this.dataGridView_paramsEditor.Rows.Remove(selectedRow);
                this.dataGridView_paramsEditor.Rows.Insert(pos, selectedRow);
                this.dataGridView_paramsEditor.ClearSelection();
                selectedRow.Selected = true;
            }
        }

        //page 3. family table view.
        enum FTContextCmd
        {
            kNone = 0,
            kCut,
            kCopy,
            kPaste,
            kDelete
        }

        private DataGridViewSelectedRowCollection m_selectedRows = null;
        private FTContextCmd m_curCmd = FTContextCmd.kNone;

        private void ToolStripMenuItem_Delete_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectRows  = this.dataGridView_familyTable.SelectedRows;

            if (selectRows.Count == 0)
            {
                SABLL.ShowInfoMsg("删除无效, 请至少选中一行！");
                return;
            }

            //double confrim when do delete.
            //
            if (SABLL.ShowConfirmMsg(String.Format("共选中{0}行, 确定删除？", selectRows.Count)) == System.Windows.Forms.DialogResult.No)
                return;

            m_curCmd = FTContextCmd.kDelete;

            for (int i = selectRows.Count - 1; i >= 0; i--)
            {
                this.dataGridView_familyTable.Rows.Remove(selectRows[i]);
            }
        }

        private void ToolStripMenuItem_Copy_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectRows = this.dataGridView_familyTable.SelectedRows;

            if (selectRows.Count == 0)
            {
                SABLL.ShowInfoMsg("拷贝无效, 请至少选中一行！");
                return;
            }

            m_curCmd = FTContextCmd.kCopy;
            m_selectedRows = selectRows;
        }

        private void ToolStripMenuItem_Paste_Click(object sender, EventArgs e)
        {
            if (m_selectedRows == null || m_selectedRows.Count == 0)
            {
                SABLL.ShowInfoMsg("粘帖无效, 请先剪切或者拷贝！");
                return;
            }

            DataGridViewSelectedRowCollection selectRows = this.dataGridView_familyTable.SelectedRows;
            int colCnt = this.dataGridView_familyTable.Columns.Count;
            switch (m_curCmd)
            {
                case FTContextCmd.kNone:
                    break;
                case FTContextCmd.kCut:
                    {
                        int insertIdx = this.dataGridView_familyTable.Rows.GetLastRow(DataGridViewElementStates.Selected);
                        if (insertIdx == -1)
                        {
                            insertIdx = this.dataGridView_familyTable.Rows.Count;
                        }

                        DataTable dt = this.dataGridView_familyTable.DataSource as DataTable;
                        if (dt == null) return;

                        List<DataRow> dtRows = new List<DataRow>();

                        foreach (DataGridViewRow row in m_selectedRows)
                        {
                            DataRow dtRow = dt.Rows[row.Index];
                            dtRows.Add(dtRow);
                            DataRow dtNewRow = dt.NewRow();
                            for (int i = 0; i < colCnt; i++)
                            {
                                dtNewRow[i] = dtRow[i];
                            }
                            dt.Rows.InsertAt(dtNewRow, ++insertIdx);
                        }

                        foreach (DataRow row in dtRows)
                        {
                            dt.Rows.Remove(row);
                        }
                        m_selectedRows = null;
                    }
                    break;
                case FTContextCmd.kCopy:
                    {
                        int insertIdx = this.dataGridView_familyTable.Rows.GetLastRow(DataGridViewElementStates.Selected);
                        if (insertIdx == -1)
                        {
                            insertIdx = this.dataGridView_familyTable.Rows.Count;
                        }

                        DataTable dt = this.dataGridView_familyTable.DataSource as DataTable;
                        if (dt == null) return;

                        foreach (DataGridViewRow row in m_selectedRows)
                        {
                            DataRow newDTRow = dt.NewRow();

                            for (int i = 0; i < colCnt; i++)
                            {
                                newDTRow[i] = row.Cells[i].Value;
                            }
                            newDTRow[0] = Guid.NewGuid().ToString();//instanceID.

                            dt.Rows.InsertAt(newDTRow, ++insertIdx);
                        }
                    }
                    break;
                case FTContextCmd.kPaste:
                    break;
                case FTContextCmd.kDelete:
                    break;
                default:
                    break;
            }
        }

        private void ToolStripMenuItem_Cut_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectRows = this.dataGridView_familyTable.SelectedRows;

            if (selectRows.Count == 0)
            {
                SABLL.ShowInfoMsg("剪切无效, 请至少选中一行！");
                return;
            }

            m_curCmd = FTContextCmd.kCut;
            m_selectedRows = selectRows;
        }

        private void contextMenuStrip_tableEdit_Opening(object sender, CancelEventArgs e)
        {
            DataGridViewSelectedRowCollection selectRows = this.dataGridView_familyTable.SelectedRows;

            if (selectRows.Count == 0)
            {
                this.ToolStripMenuItem_Copy.Enabled = false;
                this.ToolStripMenuItem_Cut.Enabled = false;
                this.ToolStripMenuItem_Delete.Enabled = false;
            }
            else
            {
                this.ToolStripMenuItem_Copy.Enabled = true;
                this.ToolStripMenuItem_Cut.Enabled = true;
                this.ToolStripMenuItem_Delete.Enabled = true;
            }

            if (m_selectedRows != null && m_selectedRows.Count > 0)
            {
                this.ToolStripMenuItem_Paste.Enabled = true;
            }
            else
            {
                this.ToolStripMenuItem_Paste.Enabled = false;
            }
        }

        private void button_SearchCellVal_Click(object sender, EventArgs e)
        {
            string searchText = this.textBox_seachCell.Text.Trim();
            this.label_SearchResult.Text = String.Empty;
            if (String.IsNullOrEmpty(searchText))
            {
                SABLL.ShowInfoMsg("搜索字符串不能为空！");
            }

            bool bClearSelection = false;
            int totalRows = this.dataGridView_familyTable.Rows.Count;
            int totalColumns = this.dataGridView_familyTable.Columns.Count;
            DataGridViewCell firstMatchCell = null;
            int totalResult = 0;
            for (int i = 0; i < totalRows; i++)
            {
                for (int j = 2; j < totalColumns; j++)
                {
                   string cellVal = Convert.ToString(this.dataGridView_familyTable.Rows[i].Cells[j].Value);
                   if (cellVal.Contains(searchText))
                   {
                       if(firstMatchCell == null)
                            firstMatchCell = this.dataGridView_familyTable.Rows[i].Cells[j];

                       if (!bClearSelection)
                       {
                           this.dataGridView_familyTable.ClearSelection();
                           bClearSelection = true;
                       }
                       this.dataGridView_familyTable.Rows[i].Cells[j].Selected = true;
                       totalResult++;
                   }
                }
            }

            this.label_SearchResult.Text = String.Format(@"共搜索到{0}个结果！", totalResult);

            if (firstMatchCell!= null && !firstMatchCell.Displayed)
            {
                this.dataGridView_familyTable.FirstDisplayedCell = firstMatchCell;
            }
        }

        private void textBox_seachCell_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button_SearchCellVal_Click(null, null);
            }
        }
    }
}
